import {
  createBrowserRouter,
  Navigate,
  useLocation,
  useNavigate,
} from "react-router-dom";
import React, { lazy, useEffect } from "react";
import { message } from "antd";

// 懒加载组件
const View = lazy(() => import("@/layout"));
const Home = lazy(() => import("@/views/Home"));
const About = lazy(() => import("@/views/About"));
const Login = lazy(() => import("@/views/Login"));
const Notfound = lazy(() => import("@/views/Notfound"));
const UserOne = lazy(() => import("@/views/User/UserOne"));
const UserTwo = lazy(() => import("@/views/User/UserTwo"));
const UserThree = lazy(() => import("@/views/User/UserThree"));
const TeamOne = lazy(() => import("@/views/Team/TeamOne"));
const TeamTwo = lazy(() => import("@/views/Team/TeamTwo"));
const TeamThree = lazy(() => import("@/views/Team/TeamThree"));

// 封装加载组件
const loadingComponent = (comp: JSX.Element) => {
  return (
    <React.Suspense fallback={<div>正在植入水马病毒...</div>}>
      {comp}
    </React.Suspense>
  );
};
const ToHome = () => {
  const navigateTo = useNavigate();
  useEffect(() => {
    console.log("12312312312");
    message.warning("请已经登录");
    navigateTo("/home");
  }, []);
  return <div></div>;
};
const ToLogin = () => {
  const navigateTo = useNavigate();
  useEffect(() => {
    navigateTo("/login");
    message.warning("请先登录");
  }, []);
  return <div></div>;
};

const BeforeRouterEnter = () => {
  const location = useLocation();
  let token = localStorage.getItem("token");
  if (token && location.pathname === "/login") {
    return <ToHome />;
  }
  if (!token && location.pathname !== "/login") {
    return <ToLogin />;
  }

  return <View />;
};
const router = createBrowserRouter([
  {
    path: "/home",
    element: <Navigate to="/" />,
  },
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "/",
    element: loadingComponent(<BeforeRouterEnter />),
    children: [
      {
        path: "/home",
        index: true,
        element: loadingComponent(<Home />),
      },
      {
        path: "/about",
        element: loadingComponent(<About />),
      },
      {
        path: "/user/user01",
        element: loadingComponent(<UserOne />),
      },
      {
        path: "/user/user02",
        element: loadingComponent(<UserTwo />),
      },
      {
        path: "/user/user03",
        element: loadingComponent(<UserThree />),
      },
      {
        path: "/team/team01",
        element: loadingComponent(<TeamOne />),
      },
      {
        path: "/team/team02",
        element: loadingComponent(<TeamTwo />),
      },
      {
        path: "/team/team03",
        element: loadingComponent(<TeamThree />),
      },
    ],
  },
  {
    path: "*",
    element: loadingComponent(<Notfound />),
  },
]);

export default router;
